package com.example.music.activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.adapter.IndexAdapter;
import com.example.music.adapter.SongAdapter;
import com.example.music.fragment.CategoryFragment;
import com.example.music.model.Song;
import com.example.music.utils.PinyinUtil;
import com.example.music.utils.SectionItemDecoration;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryDetailActivity extends AppCompatActivity {

    private static final String TAG = "CategoryDetailActivity";
    private TextView categoryNameTextView;
    private RecyclerView recyclerView;
    private RecyclerView indexRecyclerView;
    private SongAdapter songAdapter;
    private IndexAdapter indexAdapter;
    private List<Song> songList = new ArrayList<>();
    private Map<Integer, String> sectionMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_detail);

        categoryNameTextView = findViewById(R.id.category_name_text_view);
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        String categoryName = getIntent().getStringExtra("category_name");
        String categoryType = getIntent().getStringExtra("category_type");

        categoryNameTextView.setText(categoryName);

        loadSongs(categoryType, categoryName);
    }

    private void loadSongs(String categoryType, String categoryName) {
        CategoryFragment.CategoryType type = CategoryFragment.CategoryType.valueOf(categoryType);

        try (Cursor cursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DURATION
                },
                MediaStore.Audio.Media.IS_MUSIC + " != 0",
                null,
                null
        )) {
            if (cursor == null) {
                Log.e(TAG, "Failed to get cursor");
                return;
            }

            while (cursor.moveToNext()) {
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                Song song = new Song(title, artist, album, filePath);
                song.setDuration(duration);

                // 获取专辑封面
                Bitmap albumCover = getAlbumArt(filePath);
                song.setAlbumCover(albumCover);

                // 获取歌词文件
                String lyricsPath = findLyricsFile(filePath);
                song.setLyricsPath(lyricsPath);

                if (isMatched(type, song, categoryName)) {
                    songList.add(song);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Error loading songs", e);
        }

        // 中文拼音排序
        Collections.sort(songList, Comparator.comparing(song -> PinyinUtil.toPinyin(song.getTitle())));

        // 更新节索引映射
        updateSectionMap();

        // 设置Adapter
        songAdapter = new SongAdapter(songList);
        songAdapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Song song) {
                Intent intent = new Intent(CategoryDetailActivity.this, MusicActivity.class);
                intent.putExtra("position", String.valueOf(songList.indexOf(song)));
                intent.putExtra("songList", new ArrayList<>(songList)); // Pass a copy of the list
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(songAdapter);
    }

    private void updateSectionMap() {
        sectionMap.clear();
        char lastChar = '\0';
        for (int i = 0; i < songList.size(); i++) {
            String title = songList.get(i).getTitle();
            String pinyinTitle = PinyinUtil.toPinyin(title);
            if (!pinyinTitle.isEmpty()) {
                char firstChar = Character.toUpperCase(pinyinTitle.charAt(0));
                if (firstChar != lastChar) {
                    sectionMap.put(i, String.valueOf(firstChar));
                    lastChar = firstChar;
                }
            }
        }
    }

    private boolean isMatched(CategoryFragment.CategoryType type, Song song, String categoryName) {
        switch (type) {
            case BY_SINGLE:
                return song.getTitle().equals(categoryName);
            case BY_ALBUM:
                return song.getAlbum().equals(categoryName);
            case BY_ARTIST:
                return song.getArtist().equals(categoryName);
            case BY_FOLDER:
                File file = new File(song.getPath());
                return file.getParent().equals(categoryName);
            default:
                return false;
        }
    }

    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    private String findLyricsFile(String songFilePath) {
        File songFile = new File(songFilePath);
        File directory = songFile.getParentFile();
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return null;
        }

        FilenameFilter lrcFilter = (dir, name) -> name.equalsIgnoreCase(songFile.getName().replace(".mp3", ".lrc"));
        File[] lrcFiles = directory.listFiles(lrcFilter);

        if (lrcFiles != null && lrcFiles.length > 0) {
            return lrcFiles[0].getAbsolutePath();
        }

        return null;
    }
}